package com.xunwulian.web.controller.buss;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xunwulian.base.dao.BillDetailDao;
import com.xunwulian.base.entity.BillDetailEntity;
import com.xunwulian.web.controller.BaseController;
import com.xunwulian.web.entity.BillDetailEntityWraper;
import com.xunwulian.web.util.Const;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/billDetail")
public class BillDetailController extends BaseController {

    @Autowired
    private BillDetailDao billDetailDao;

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    /**
     * 列表
     *
     * @param billId
     * @return
     */
    @RequestMapping(value = "/billDetail/list")
    public ModelAndView list(@RequestParam("billId") String billId) {

        ModelAndView mv = this.getModelAndView();

        logBefore(logger, "列表billId:" + billId);

        List<BillDetailEntity> list = billDetailDao.getByBillId(billId);

        logger.info("list:" + gson.toJson(list));

        List<BillDetailEntityWraper> wrapers = list.stream().map(p -> new BillDetailEntityWraper(p)).collect(Collectors.toList());

        logger.info("wraper:" + gson.toJson(wrapers));

        mv.addObject("varList", wrapers);

        mv.setViewName("system/bill/billDetail_list");

        mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限

        return mv;
    }

    /**
     * @return
     */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }


    /**
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format,
                true));
    }

}
